import 'package:flutter/material.dart';
import '../../../core/theme/theme.dart';
import '../common/custom_text_field.dart';
import '../../../data/api/auth_api.dart';
import '../../../core/exceptions/app_exception.dart';
import 'package:provider/provider.dart';
import '../../../domain/providers/auth_provider.dart';
import '../../screens/home/home_screen.dart';

enum AuthMode { login, register }

class AuthDrawer extends StatefulWidget {
  const AuthDrawer({Key? key}) : super(key: key);

  @override
  State<AuthDrawer> createState() => _AuthDrawerState();
}

class _AuthDrawerState extends State<AuthDrawer>
    with SingleTickerProviderStateMixin {
  final _formKey = GlobalKey<FormState>();
  final _usernameController = TextEditingController();
  final _emailController = TextEditingController();
  final _passwordController = TextEditingController();
  final _confirmPasswordController = TextEditingController();
  bool _isLoading = false;
  AuthMode _authMode = AuthMode.login;
  String? _errorMessage;

  // 动画控制器
  late final AnimationController _animationController;
  late final Animation<double> _heightFactorAnimation;
  late final Animation<Offset> _slideAnimation;

  @override
  void initState() {
    super.initState();
    _animationController = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 300),
    );

    _heightFactorAnimation = Tween<double>(
      begin: 0.60, // 减小登录表单高度
      end: 0.70, // 减小注册表单高度
    ).animate(
      CurvedAnimation(parent: _animationController, curve: Curves.easeInOut),
    );

    _slideAnimation = Tween<Offset>(
      begin: Offset.zero,
      end: const Offset(0, -1),
    ).animate(
      CurvedAnimation(parent: _animationController, curve: Curves.easeInOut),
    );
  }

  @override
  void dispose() {
    _animationController.dispose();
    _usernameController.dispose();
    _emailController.dispose();
    _passwordController.dispose();
    _confirmPasswordController.dispose();
    super.dispose();
  }

  void _switchAuthMode() async {
    if (_authMode == AuthMode.login) {
      setState(() {
        _authMode = AuthMode.register;
        _errorMessage = null;
      });
      await _animationController.forward();
    } else {
      await _animationController.reverse();
      setState(() {
        _authMode = AuthMode.login;
        _errorMessage = null;
      });
    }
  }

  void _handleSubmit() async {
    // 关闭键盘
    FocusScope.of(context).unfocus();

    if (_formKey.currentState?.validate() ?? false) {
      setState(() {
        _isLoading = true;
        _errorMessage = null;
      });

      try {
        final authProvider = Provider.of<AuthProvider>(context, listen: false);

        if (_authMode == AuthMode.login) {
          // 登录逻辑
          debugPrint('开始登录: ${_usernameController.text}');
          await authProvider.login(
            username: _usernameController.text.trim(),
            password: _passwordController.text.trim(),
          );

          if (mounted) {
            debugPrint('登录成功，导航到首页');
            // 登录成功后导航到首页
            Navigator.of(context).pushReplacement(
              MaterialPageRoute(builder: (context) => const HomeScreen()),
            );
          }
        } else {
          // 注册逻辑
          await authProvider.register(
            username: _usernameController.text.trim(),
            email: _emailController.text.trim(),
            password: _passwordController.text.trim(),
          );

          if (mounted) {
            // 注册成功后显示提示并切换到登录界面
            ScaffoldMessenger.of(
              context,
            ).showSnackBar(const SnackBar(content: Text('注册成功，请登录')));
            _switchAuthMode();
          }
        }
      } catch (e) {
        if (mounted) {
          debugPrint('认证失败: $e');
          setState(() {
            _errorMessage = e is AppException ? e.message : '操作失败，请稍后重试';
          });
        }
      } finally {
        if (mounted) {
          setState(() {
            _isLoading = false;
          });
        }
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    final screenHeight = MediaQuery.of(context).size.height;
    // 计算合适的内边距
    final bottomPadding = MediaQuery.of(context).padding.bottom; // 获取底部安全区域高度
    final topPadding = 32.0;
    final horizontalPadding = 32.0;

    return AnimatedBuilder(
      animation: _heightFactorAnimation,
      builder: (context, child) {
        return Positioned(
          bottom: 0,
          left: 0,
          right: 0,
          height: screenHeight * _heightFactorAnimation.value,
          child: Container(
            decoration: BoxDecoration(
              color: context.isDarkMode ? context.surfaceColor : Colors.white,
              borderRadius: const BorderRadius.only(
                topLeft: Radius.circular(32),
                topRight: Radius.circular(32),
              ),
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withOpacity(0.1),
                  blurRadius: 10,
                  offset: const Offset(0, -5),
                ),
              ],
            ),
            child: SingleChildScrollView(
              padding: EdgeInsets.only(
                top: topPadding,
                left: horizontalPadding,
                right: horizontalPadding,
                bottom: bottomPadding + 16, // 底部安全区域 + 16像素的额外间距
              ),
              child: Form(
                key: _formKey,
                child: ClipRect(
                  child: Stack(
                    children: [
                      SlideTransition(
                        position: _slideAnimation,
                        child: _buildLoginForm(),
                      ),
                      if (_authMode == AuthMode.register)
                        SlideTransition(
                          position: Tween<Offset>(
                            begin: const Offset(0, 1),
                            end: Offset.zero,
                          ).animate(_animationController),
                          child: _buildRegisterForm(),
                        ),
                    ],
                  ),
                ),
              ),
            ),
          ),
        );
      },
    );
  }

  Widget _buildLoginForm() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        Text(
          '欢迎回来！',
          style: context.headline2.copyWith(
            color: context.textColor,
            fontWeight: FontWeight.bold,
          ),
        ),
        const SizedBox(height: 24),

        CustomTextField(
          label: '用户名',
          hint: '请输入用户名',
          controller: _usernameController,
          validator: (value) {
            if (value == null || value.isEmpty) {
              return '请输入用户名';
            }
            return null;
          },
        ),
        const SizedBox(height: 16),

        CustomTextField(
          label: '密码',
          hint: '请输入密码',
          isPassword: true,
          controller: _passwordController,
          validator: (value) {
            if (value == null || value.isEmpty) {
              return '请输入密码';
            }
            return null;
          },
        ),
        const SizedBox(height: 12),

        // 错误信息行
        if (_errorMessage != null)
          Container(
            margin: const EdgeInsets.only(bottom: 8),
            padding: const EdgeInsets.symmetric(vertical: 6, horizontal: 10),
            decoration: BoxDecoration(
              color: Colors.red.withOpacity(0.1),
              borderRadius: BorderRadius.circular(6),
              border: Border.all(color: Colors.red.withOpacity(0.5), width: 1),
            ),
            child: Row(
              children: [
                const Icon(Icons.error_outline, color: Colors.red, size: 16),
                const SizedBox(width: 8),
                Expanded(
                  child: Text(
                    _errorMessage!,
                    style: TextStyle(color: Colors.red.shade700, fontSize: 13),
                  ),
                ),
                IconButton(
                  padding: EdgeInsets.zero,
                  constraints: const BoxConstraints(
                    minWidth: 20,
                    minHeight: 20,
                  ),
                  iconSize: 16,
                  icon: const Icon(Icons.close, color: Colors.red),
                  onPressed: () {
                    setState(() {
                      _errorMessage = null;
                    });
                  },
                ),
              ],
            ),
          ),

        // 忘记密码按钮，与错误消息分开放置
        Align(
          alignment: Alignment.centerRight,
          child: TextButton(
            onPressed: () {
              // TODO: 实现忘记密码功能
            },
            child: Text(
              '忘记密码？',
              style: context.bodyText2.copyWith(
                color: context.textSecondaryColor,
              ),
            ),
          ),
        ),
        const SizedBox(height: 24),

        _buildSubmitButton('登 录'),
        const SizedBox(height: 16),

        _buildAuthSwitchPrompt('还没有账号？', '立即注册'),
      ],
    );
  }

  Widget _buildRegisterForm() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        Text(
          '创建账号',
          style: context.headline2.copyWith(
            color: context.textColor,
            fontWeight: FontWeight.bold,
          ),
        ),
        const SizedBox(height: 24),

        CustomTextField(
          label: '用户名',
          hint: '请输入用户名',
          controller: _usernameController,
          validator: (value) {
            if (value == null || value.isEmpty) {
              return '请输入用户名';
            }
            if (value.length < 3) {
              return '用户名至少需要3个字符';
            }
            return null;
          },
        ),
        const SizedBox(height: 16),

        CustomTextField(
          label: '邮箱',
          hint: '请输入邮箱',
          controller: _emailController,
          keyboardType: TextInputType.emailAddress,
          validator: (value) {
            if (value == null || value.isEmpty) {
              return '请输入邮箱';
            }
            if (!RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$').hasMatch(value)) {
              return '请输入有效的邮箱地址';
            }
            return null;
          },
        ),
        const SizedBox(height: 16),

        CustomTextField(
          label: '密码',
          hint: '请输入密码',
          isPassword: true,
          controller: _passwordController,
          validator: (value) {
            if (value == null || value.isEmpty) {
              return '请输入密码';
            }
            if (value.length < 6) {
              return '密码至少需要6个字符';
            }
            return null;
          },
        ),
        const SizedBox(height: 16),

        CustomTextField(
          label: '确认密码',
          hint: '请再次输入密码',
          isPassword: true,
          controller: _confirmPasswordController,
          validator: (value) {
            if (value == null || value.isEmpty) {
              return '请再次输入密码';
            }
            if (value != _passwordController.text) {
              return '两次输入的密码不一致';
            }
            return null;
          },
        ),
        const SizedBox(height: 24),

        _buildSubmitButton('注 册'),
        const SizedBox(height: 16),

        _buildAuthSwitchPrompt('已有账号？', '返回登录'),
      ],
    );
  }

  Widget _buildSubmitButton(String text) {
    return SizedBox(
      height: 56,
      child: ElevatedButton(
        onPressed: _isLoading ? null : _handleSubmit,
        style: ElevatedButton.styleFrom(
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(16),
          ),
        ),
        child:
            _isLoading
                ? const SizedBox(
                  width: 24,
                  height: 24,
                  child: CircularProgressIndicator(
                    strokeWidth: 2,
                    valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                  ),
                )
                : Text(text),
      ),
    );
  }

  Widget _buildAuthSwitchPrompt(String prompt, String actionText) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Text(
          prompt,
          style: context.bodyText2.copyWith(color: context.textSecondaryColor),
        ),
        TextButton(
          onPressed: _switchAuthMode,
          child: Text(
            actionText,
            style: context.bodyText2.copyWith(
              color: context.primaryColor,
              fontWeight: FontWeight.bold,
            ),
          ),
        ),
      ],
    );
  }
}
